﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BenzInfo.Hockey.Grenadiers.Models;
using BenzInfo.Hockey.Grenadiers.Utils;
using System.Net;
using System.Net.Mail;
using System.Text; 

namespace BenzInfo.Hockey.Grenadiers.Controllers
{
    public class HomeController : BaseController
    {
        private GrenadiersContext db = new GrenadiersContext();

        private const string BASE_PATH = "~/Content/images/posts";

        public ViewResult Index()
        {
            ViewBag.Ads = db.Ads.Where(m => m.Key == "Ads").ToList();

            ViewBag.Survey = db.Questions.Where(m => m.Key == "Questions").Single();

            ViewBag.Hotnews = GetHotNews();

            ViewBag.NextGame = db.Games.Where(m => m.DateEnd > DateTime.Now).OrderBy(m => m.DateStart).FirstOrDefault();
            ViewBag.LastGame = db.Games.Where(m => m.DateEnd < DateTime.Now).OrderByDescending(m => m.DateEnd).FirstOrDefault();

            List<Post> posts = db.Posts.Where(m => m.Key == "News").OrderByDescending(m => m.DateCreated).Take(5).ToList();

            return View(posts);
        }

        public HotNews GetHotNews()
        {
            HotNews retHotNews = db.HotNews.SingleOrDefault();

            if (retHotNews == null)
            {
                retHotNews = new HotNews()
                {
                    Id = 1,
                    ContentEN = "Welcome on the Grenadiers website!",
                    ContentFR = "Bienvenue sur le site des Grenadiers!"
                };

                db.HotNews.Attach(retHotNews);
                db.HotNews.Add(retHotNews);
                db.SaveChanges();
            }

            return db.HotNews.First();
        }

        public ActionResult EditHotNews()
        {
            return PartialView(GetHotNews());
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult EditHotNews(HotNews hotnews)
        {
            if (ModelState.IsValid)
            {
                db.Entry(hotnews).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return PartialView(hotnews);
        }

        public ActionResult ChangeEmailRecipient()
        {
            NewsletterEmail email= db.NewsletterEmail.FirstOrDefault();

            if (email == null)
            {
                email = new NewsletterEmail() { EmailRecipient = "Please@Change.Email" };
                db.NewsletterEmail.Attach(email);
                db.NewsletterEmail.Add(email);
                db.SaveChanges();
            }

            return PartialView("ChangeEmailRecipient", email);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult ChangeEmailRecipient(NewsletterEmail newRecipient)
        {
            if (ModelState.IsValid)
            {
                db.Entry(newRecipient).State = EntityState.Modified;
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        public ActionResult AddNewsletterInscription()
        {
            return PartialView("AddNewsletterInscription");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult AddNewsletterInscription(NewsletterIncsription inscription)
        {
            foreach(NewsletterIncsription i in db.NewsletterIncsription)
            {
                if(i.Email.CompareTo(inscription.Email) == 0)
                    return RedirectToAction("Index");
            }   

            if (ModelState.IsValid)
            {
                db.NewsletterIncsription.Attach(inscription);
                db.NewsletterIncsription.Add(inscription);
                db.SaveChanges();

                //Send an email to the recipient
                NewsletterEmail recipient = db.NewsletterEmail.FirstOrDefault();

                if (recipient != null)
                {
                    try
                    {
                        string smtpHost = System.Configuration.ConfigurationManager.AppSettings["SMTPHost"];
                        int smtpPort = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["SMTPPort"]);
                        string smtpUser = System.Configuration.ConfigurationManager.AppSettings["SMTPUser"];
                        string smtpPass = System.Configuration.ConfigurationManager.AppSettings["SMTPPass"];

                        MailMessage message = new MailMessage();

                        message.To.Add(new MailAddress(recipient.EmailRecipient));
                        message.Subject = "Newsletter inscription";
                        message.From = new MailAddress("postmaster@grenadiersdechateauguay.com");
                        message.Body = "First name: " + inscription.FirstName + "\n";
                        message.Body += "Last name: " + inscription.LastName + "\n";
                        message.Body += "Email: " + inscription.Email + "\n";

                        SmtpClient smtp = new SmtpClient();

                        smtp.Host = smtpHost;
                        smtp.Port = smtpPort;
                        smtp.UseDefaultCredentials = false;
                        smtp.Credentials = new NetworkCredential(smtpUser, smtpPass);

                        smtp.Send(message);
                    }
                    catch (Exception e) 
                    {
                        string test = e.Message;
                    }
                }
            }

            return RedirectToAction("Index");
        }

        public ActionResult AddHomeNews()
        {
            return PartialView("AddHomeNews");
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult AddHomeNews(Post news, HttpPostedFileBase inputFile)
        {
            
            if (inputFile != null)
            {
                using (Image img = Image.FromStream(inputFile.InputStream))
                {
                    string ext = inputFile.FileName.Split('.')[inputFile.FileName.Split('.').Length - 1];
                    string filename = string.Format("{0:000}.{1}", DateTime.Now.Ticks, ext);
                    string filepath = string.Format("{0}/{1}", Server.MapPath(BASE_PATH), filename);

                    ImageHelper.Save(img, filepath, ext);

                    news.Picture = filename;
                }
            }

            news.UserCreatedBy = ViewBag.CurrentUser;
            news.DateCreated = DateTime.Now;
            news.UserModifiedBy = ViewBag.CurrentUser;
            news.DateModified = DateTime.Now;
            news.Key = "News";

            ModelState.Remove("UserCreatedBy");
            ModelState.Remove("UserModifiedBy");
            ModelState.Remove("Key");

            if (ModelState.IsValid)
            {
                db.Posts.Attach(news);
                db.Posts.Add(news);
                db.SaveChanges();
            }

            return RedirectToAction("Index");
        }

        //
        // GET: /Pictures/Edit/5

        public ActionResult EditHomeNews(int id)
        {
            Post post = db.Posts.Find(id);

            return PartialView("EditHomeNews", post);
        }

        //
        // POST: /Tickets/Edit/5

        [HttpPost]
        public ActionResult EditHomeNews(Post post)
        {
            Post postdb = db.Posts.Find(post.Id);

            User UserCreatedBy = postdb.UserCreatedBy;
            DateTime DateCreated = postdb.DateCreated;
            User UserModifiedBy = ViewBag.CurrentUser;
            DateTime DateModified = DateTime.Now;

            TryUpdateModel(postdb);

            postdb.UserCreatedBy = UserCreatedBy;
            postdb.DateCreated = DateCreated;
            postdb.UserModifiedBy = UserModifiedBy;
            postdb.DateModified = DateModified;

            //To make the modelstate valid ...
            ModelState.Remove("UserCreatedBy");
            ModelState.Remove("UserModifiedBy");

            if (ModelState.IsValid)
            {
                db.Posts.Attach(postdb);
                db.Entry(postdb).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return PartialView("EditHomeNews", post);
        }

        public ActionResult DeleteHomeNews(int id)
        {
            Post post = db.Posts.Find(id);
            db.Posts.Remove(post);
            db.SaveChanges();

            return RedirectToAction("Index");
        }


        public JsonResult SubmitSurvey(int optionSelected)
        {
            // logic for submitting feedback omitted
            
            Answer answer = new Answer();
            answer.OptionSelected = optionSelected;
            answer.DateCreated = DateTime.Now;

            db.Answers.Attach(answer);
            db.Answers.Add(answer);
            db.SaveChanges();

            SubmitResult result = new SubmitResult();
                result.message = @BenzInfo.Hockey.Grenadiers.Resources.Dictionary.AnswerSurvey;
                result.success = true;
            return Json(result, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet); 
        }

        public ActionResult Culture(string lang)
        {
            Session["Lang"] = lang;

            return Redirect(Request.UrlReferrer.ToString());
        }
    }
}
